package com.ysd.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 姝ょ被涓皝瑁呬竴浜涘父鐢ㄧ殑瀛楃涓叉搷浣溿�� 鎵�鏈夋柟娉曢兘鏄潤鎬佹柟娉曪紝涓嶉渶瑕佺敓鎴愭绫荤殑瀹炰緥锛� 涓洪伩鍏嶇敓鎴愭绫荤殑瀹炰緥锛屾瀯閫犳柟娉曡鐢虫槑涓簆rivate绫诲瀷鐨勩��
 * 
 * @since 0.1
 */
public class StringUtil {
	private static String strChineseFirstPY = "";// 鍐呭澶暱璇峰埌http://jshuwei.org.cn涓婁笅杞�

	/** 
	 * 鑾峰彇鍗佸叚杩涘埗鐨勯鑹蹭唬鐮�.渚嬪 "#6E36B4" , For HTML , 
	 * @return String 
	 */ 
	public static String getRandColorCode(){ 
	 String r,g,b; 
	 Random random = new Random(); 
	 r = Integer.toHexString(random.nextInt(256)).toUpperCase(); 
	 g = Integer.toHexString(random.nextInt(256)).toUpperCase(); 
	 b = Integer.toHexString(random.nextInt(256)).toUpperCase(); 

	 r = r.length()==1 ? "0" + r : r ; 
	 g = g.length()==1 ? "0" + g : g ; 
	 b = b.length()==1 ? "0" + b : b ; 

	 return r+g+b; 
	 } 
	
	/**
	 * 璁＄畻鐧惧垎鏁�
	 */
	public static String getPercent(int x, int total) {
		String result = "";// 鎺ュ彈鐧惧垎姣旂殑鍊�
		double x_double = x * 1.0;
		double tempresult = (double) x / total;
		// NumberFormat nf = NumberFormat.getPercentInstance(); 娉ㄩ噴鎺夌殑涔熸槸涓�绉嶆柟娉�
		// nf.setMinimumFractionDigits( 2 ); 淇濈暀鍒板皬鏁扮偣鍚庡嚑浣�
		DecimalFormat df1 = new DecimalFormat("0.00%"); // ##.00%
														// 鐧惧垎姣旀牸寮忥紝鍚庨潰涓嶈冻2浣嶇殑鐢�0琛ラ綈
		// result=nf.format(tempresult);
		result = df1.format(tempresult);
		return result;
	}

	/**
	 * 灏嗕竴瀛楃涓茶浆鎹㈡垚鎷奸煶棣栧瓧姣�
	 * 
	 * @since 1.1
	 * @param strText
	 *            瀛楃涓�
	 * @return 瀛楃涓插搴旂殑鎷奸煶棣栧瓧姣�
	 */
	public static String getFirstPY(String strText) {
		if (strText == null || strText.trim().length() == 0)
			return "";
		String ret = "";
		for (int i = 0; i < strText.length(); i++) {
			char ch = strText.charAt(i);
			if ('\u4E00' <= ch && '\u9FA5' >= ch)
				ret = ret + strChineseFirstPY.charAt(ch - 19968);
			else
				ret = ret + ch;
		}

		return ret;
	}
	/*
	 *鍒ゆ柇瀛楃涓叉槸鍚︽槸鏁板瓧 
	 * 
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}// 鐢╝scii鐮佸垽鏂暣鍨� ...

	/**
	 * 鏇挎崲瀛楃涓�
	 * 
	 * @since 1.1
	 * @param strSc
	 *            闇�瑕佽繘琛屾浛鎹㈢殑瀛楃涓�
	 * @param oldStr
	 *            婧愬瓧绗︿覆
	 * @param newStr
	 *            鏇挎崲鍚庣殑瀛楃涓�
	 * @return 鏇挎崲鍚庡搴旂殑瀛楃涓�
	 */
	public static String replace(String strSc, String oldStr, String newStr) {
		String ret = strSc;
		if (ret != null && oldStr != null && newStr != null) {
			ret = strSc.replaceAll(oldStr, newStr);
		}
		return ret;
	}

	/**
	 * 鏇挎崲瀛楃涓诧紝淇java.lang.String绫荤殑replaceAll鏂规硶鏃剁涓�鍙傛暟鏄瓧绗︿覆甯搁噺姝ｅ垯鏃�(濡傦細"address".
	 * replaceAll("dd","$");)鐨勬姏鍑哄紓甯革細java.lang.StringIndexOutOfBoundsException:
	 * String index out of range: 1鐨勯棶棰樸��
	 * 
	 * @since 1.2
	 * @param strSc
	 *            闇�瑕佽繘琛屾浛鎹㈢殑瀛楃涓�
	 * @param oldStr
	 *            婧愬瓧绗︿覆
	 * @param newStr
	 *            鏇挎崲鍚庣殑瀛楃涓�
	 * @return 鏇挎崲鍚庡搴旂殑瀛楃涓�
	 */
	public static String replaceAll(String strSc, String oldStr, String newStr) {
		int i = -1;
		while ((i = strSc.indexOf(oldStr)) != -1) {
			strSc = new StringBuffer(strSc.substring(0, i)).append(newStr)
					.append(strSc.substring(i + oldStr.length())).toString();
		}
		return strSc;
	}

	/**
	 * 灏嗗瓧绗︿覆杞崲鎴怘TML鏍煎紡鐨勫瓧绗︿覆
	 * 
	 * @since 1.1
	 * @param str
	 *            闇�瑕佽繘琛岃浆鎹㈢殑瀛楃涓�
	 * @return 杞崲鍚庣殑瀛楃涓�
	 */
	public static String toHtml(String str) {
		String html = str;
		if (str == null || str.length() == 0) {
			return "";
		} else {
			html = replace(html, "&", "&amp;");
			html = replace(html, "<", "&lt;");
			html = replace(html, ">", "&gt;");
			html = replace(html, "\r\n", "\n");
			html = replace(html, "\n", "<br>\n");
			html = replace(html, "\"", "&quot;");
			html = replace(html, " ", "&nbsp;");
			return html;
		}
	}

	/**
	 * 灏咹TML鏍煎紡鐨勫瓧绗︿覆杞崲鎴愬父瑙勬樉绀虹殑瀛楃涓�
	 * 
	 * @since 1.1
	 * @param str
	 *            闇�瑕佽繘琛岃浆鎹㈢殑瀛楃涓�
	 * @return 杞崲鍚庣殑瀛楃涓�
	 */
	public static String toText(String str) {
		String text = str;
		if (str == null || str.length() == 0) {
			return "";
		} else {
			text = replace(text, "&amp;", "&");
			text = replace(text, "&lt;", "<");
			text = replace(text, "&gt;", ">");
			text = replace(text, "<br>\n", "\n");
			text = replace(text, "<br>", "\n");
			text = replace(text, "&quot;", "\"");
			text = replace(text, "&nbsp;", " ");
			return text;
		}
	}

	/**
	 * 灏嗕竴瀛楃涓叉暟缁勪互鏌愮壒瀹氱殑瀛楃涓蹭綔涓哄垎闅旀潵鍙樻垚瀛楃涓�
	 * 
	 * @since 1.0
	 * @param strs
	 *            瀛楃涓叉暟缁�
	 * @param token
	 *            鍒嗛殧瀛楃涓�
	 * @return 浠oken涓哄垎闅旂殑瀛楃涓�
	 */
	public static String join(String[] strs, String token) {
		if (strs == null)
			return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < strs.length; i++) {
			if (i != 0)
				sb.append(token);
			sb.append(strs[i]);
		}
		return sb.toString();
	}

	/**
	 * 灏嗕竴瀛楃涓蹭互鏌愮壒瀹氱殑瀛楃涓蹭綔涓哄垎闅旀潵鍙樻垚瀛楃涓叉暟缁�
	 * 
	 * @since 1.0
	 * @param str
	 *            闇�瑕佹媶鍒嗙殑瀛楃涓�("@12@34@56")
	 * @param token
	 *            鍒嗛殧瀛楃涓�("@")
	 * @return 浠oken涓哄垎闅旂殑鎷嗗垎寮�鐨勫瓧绗︿覆鏁扮粍
	 */
	public static String[] split(String str, String token) {
		// String temp = str.substring(1, str.length());
		String temp = str;
		return temp.split(token);
	}

	/**
	 * 楠岃瘉瀛楃涓插悎娉曟��
	 * 
	 * @since 1.0
	 * @param str
	 *            闇�瑕侀獙璇佺殑瀛楃涓�
	 * @param test
	 *            闈炴硶瀛楃涓诧紙濡傦細"~!#$%^&*()',;:?"锛�
	 * @return true:闈炴硶;false:鍚堟硶
	 */
	public static boolean check(String str, String test) {
		if (str == null || str.equals(""))
			return true;
		boolean flag = false;
		for (int i = 0; i < test.length(); i++) {
			if (str.indexOf(test.charAt(i)) != -1) {
				flag = true;
				break;
			}
		}
		return flag;
	}

	/**
	 * 灏嗘暟鍊煎瀷瀛楃涓茶浆鎹㈡垚Integer鍨�
	 * 
	 * @since 1.0
	 * @param str
	 *            闇�瑕佽浆鎹㈢殑瀛楃鍨嬪瓧绗︿覆
	 * @param ret
	 *            杞崲澶辫触鏃惰繑鍥炵殑鍊�
	 * @return 鎴愬姛鍒欒繑鍥炶浆鎹㈠悗鐨処nteger鍨嬪�硷紱澶辫触鍒欒繑鍥瀝et
	 */
	public static Integer String2Integer(String str, Integer ret) {
		try {
			return Integer.parseInt(str);
		} catch (NumberFormatException e) {
			return ret;
		}
	}

	// 鍒ゆ柇瀛楃涓叉槸鍚︽槸鏁板瓧
	// public static boolean isNumeric(String str) {
	// if (str.matches("\\d *")) {
	// return true;
	// } else {
	// return false;
	// }
	// }

	/**
	 * 灏嗘暟鍊煎瀷杞崲鎴愬瓧绗︿覆
	 * 
	 * @since 1.0
	 * @param it
	 *            闇�瑕佽浆鎹㈢殑Integer鍨嬪��
	 * @param ret
	 *            杞崲澶辫触鐨勮繑鍥炲��
	 * @return 鎴愬姛鍒欒繑鍥炶浆鎹㈠悗鐨勫瓧绗︿覆锛涘け璐ュ垯杩斿洖ret
	 */
	public static String Integer2String(Integer it, String ret) {
		try {
			return Integer.toString(it);
		} catch (NumberFormatException e) {
			return ret;
		}
	}

	/**
	 * 姣旇緝涓ゅ瓧绗︿覆澶у皬(ASCII鐮侀『搴�)
	 * 
	 * @since 1.1
	 * @param str1
	 *            鍙備笌姣旇緝鐨勫瓧绗︿覆1
	 * @param str2
	 *            鍙備笌姣旇緝鐨勫瓧绗︿覆2
	 * @return str1>str2:1;str1<str2:-1;str1=str2:0
	 */
	public static int compare(String str1, String str2) {//
		if (str1.equals(str2)) {
			return 0;
		}
		int str1Length = str1.length();
		int str2Length = str2.length();
		int length = 0;
		if (str1Length > str2Length) {
			length = str2Length;
		} else {
			length = str1Length;
		}
		for (int i = 0; i < length; i++) {
			if (str1.charAt(i) > str2.charAt(i)) {
				return 1;
			}
		}
		return -1;
	}

	/**
	 * 灏嗛樋鎷変集鏁板瓧鐨勯挶鏁拌浆鎹㈡垚涓枃鏂瑰紡
	 * 
	 * @since 1.1
	 * @param num
	 *            闇�瑕佽浆鎹㈢殑閽辩殑闃挎媺浼暟瀛楀舰寮�
	 * @return 杞崲鍚庣殑涓枃褰㈠紡
	 */
	public static String num2Chinese(double num) {
		String result = "";
		String str = Double.toString(num);
		if (str.contains(".")) {
			String begin = str.substring(0, str.indexOf("."));
			String end = str.substring(str.indexOf(".") + 1, str.length());
			byte[] b = begin.getBytes();
			int j = b.length;
			for (int i = 0, k = j; i < j; i++, k--) {
				result += getConvert(begin.charAt(i));
				if (!"闆�".equals(result.charAt(result.length() - 1) + "")) {
					result += getWei(k);
				}
				System.out.println(result);

			}
			for (int i = 0; i < result.length(); i++) {
				result = result.replaceAll("闆堕浂", "闆�");
			}
			if ("闆�".equals(result.charAt(result.length() - 1) + "")) {
				result = result.substring(0, result.length() - 1);
			}
			result += "鍏�";
			byte[] bb = end.getBytes();
			int jj = bb.length;
			for (int i = 0, k = jj; i < jj; i++, k--) {
				result += getConvert(end.charAt(i));
				if (bb.length == 1) {
					result += "瑙�";
				} else if (bb.length == 2) {
					result += getFloat(k);
				}
			}
		} else {
			byte[] b = str.getBytes();
			int j = b.length;
			for (int i = 0, k = j; i < j; i++, k--) {
				result += getConvert(str.charAt(i));
				result += getWei(k);
			}
		}
		return result;
	}

	private static String getConvert(char num) {
		if (num == '0') {
			return "闆�";
		} else if (num == '1') {
			return "涓�";
		} else if (num == '2') {
			return "浜�";
		} else if (num == '3') {
			return "涓�";
		} else if (num == '4') {
			return "鍥�";
		} else if (num == '5') {
			return "浜�";
		} else if (num == '6') {
			return "鍏�";
		} else if (num == '7') {
			return "涓�";
		} else if (num == '8') {
			return "鍏�";
		} else if (num == '9') {
			return "涔�";
		} else {
			return "";
		}
	}

	private static String getFloat(int num) {
		if (num == 2) {
			return "瑙�";
		} else if (num == 1) {
			return "鍒�";
		} else {
			return "";
		}
	}

	private static String getWei(int num) {
		if (num == 1) {
			return "";
		} else if (num == 2) {
			return "鍗�";
		} else if (num == 3) {
			return "鐧�";
		} else if (num == 4) {
			return "鍗�";
		} else if (num == 5) {
			return "涓�";
		} else if (num == 6) {
			return "鍗�";
		} else if (num == 7) {
			return "鐧�";
		} else if (num == 8) {
			return "鍗�";
		} else if (num == 9) {
			return "浜�";
		} else if (num == 10) {
			return "鍗�";
		} else if (num == 11) {
			return "鐧�";
		} else if (num == 12) {
			return "鍗�";
		} else if (num == 13) {
			return "鍏�";
		} else {
			return "";
		}
	}

	/**
	 * 灏嗗瓧绗︿覆鐨勯瀛楁瘝鏀逛负澶у啓
	 * 
	 * @since 1.2
	 * @param str
	 *            闇�瑕佹敼鍐欑殑瀛楃涓�
	 * @return 鏀瑰啓鍚庣殑瀛楃涓�
	 */
	public static String firstToUpper(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	/**
	 * 闈炵┖妫�楠� is==true:琛ㄧず涓嶄负绌�
	 */
	public static boolean isNull(String str) {
		if (str == null || str.equals("") || str.equals("null")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * list闈炵┖妫�楠� is==true:琛ㄧず涓嶄负绌�
	 */
	public static boolean isNullList(List list) {
		if (list == null || list.isEmpty() || list.size() == 0) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isNullOrEmpty(Object obj) {
		return obj == null || "".equals(obj.toString());
	}

	public static String toString(Object obj) {
		if (obj == null)
			return "null";
		return obj.toString();
	}

	public static String join(Collection s, String delimiter) {
		StringBuffer buffer = new StringBuffer();
		Iterator iter = s.iterator();
		while (iter.hasNext()) {
			buffer.append(iter.next());
			if (iter.hasNext()) {
				buffer.append(delimiter);
			}
		}
		return buffer.toString();
	}

	// 鑾峰彇uuid
	public static String getUuid() {
		String str = "";
		UUID uuid = UUID.randomUUID();
		str = uuid.toString().replaceAll("-", "");

		return str;
	}
	/**
	* 灏嗘枃浠跺悕涓殑姹夊瓧杞负UTF8缂栫爜鐨勪覆,浠ヤ究涓嬭浇鏃惰兘姝ｇ‘鏄剧ず鍙﹀瓨鐨勬枃浠跺悕.
	* @param s 鍘熸枃浠跺悕
	* @return 閲嶆柊缂栫爜鍚庣殑鏂囦欢鍚�
	*/
   public static String toUtf8String(String s) {
	StringBuffer sb = new StringBuffer();
	for (int i = 0; i < s.length(); i++) {
	 char c = s.charAt(i);
	 if (c >= 0 && c <= 255) {
	  sb.append(c);
	 } else {
	  byte[] b;
	  try {
	   b = Character.toString(c).getBytes("UTF-8");
	  } catch (Exception ex) {
	   System.out.println(ex);
	   b = new byte[0];
	  }
	  for (int j = 0; j < b.length; j++) {
	   int k = b[j];
	   if (k < 0)
		k += 256;
	   sb.append("%" + Integer.toHexString(k).toUpperCase());
	  }
	 }
	}
	return sb.toString();
   }
   
	/**
	 * 鍙戦�丠ttpPost璇锋眰
	 * 
	 * @param strURL
	 *            鏈嶅姟鍦板潃
	 * @param params
	 *            json瀛楃涓�,渚嬪: "{ \"id\":\"12345\" }" ;鍏朵腑灞炴�у悕蹇呴』甯﹀弻寮曞彿<br/>
	 * @return 鎴愬姛:杩斿洖json瀛楃涓�<br/>
	 */
	public static String doPostSomeThing(String strURL, String params) {
		System.out.print("url:"+strURL+"--");
		System.out.println("params:"+params);
		String result = "";
		//@SuppressWarnings("unused")
		//String currenttime=DateUtils.formatDateTimeByDate(new Date());
		try {
			URL url = new URL(strURL);// 鍒涘缓杩炴帴
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestMethod("POST"); // 璁剧疆璇锋眰鏂瑰紡POST
			System.out.println(connection.toString());
			connection.setRequestProperty("Accept", "application/json"); // 璁剧疆鎺ユ敹鏁版嵁鐨勬牸寮�
			connection.setRequestProperty("Content-Type", "application/json"); // 璁剧疆鍙戦�佹暟鎹殑鏍煎紡
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); // utf-8缂栫爜
			out.append(params);
			out.flush();
			out.close();
			// 璇诲彇鍝嶅簲
			int length = (int) connection.getContentLength();// 鑾峰彇闀垮害
			InputStream is = connection.getInputStream();
			if (length != -1) {
				byte[] data = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) > 0) {
					System.arraycopy(temp, 0, data, destPos, readLen);
					destPos += readLen;
				}
				result = new String(data, "utf-8"); // utf-8缂栫爜
//				System.out.println(result);
				
			}
		} catch (IOException e) {
			//e.printStackTrace();
			result=e.toString();
		}
		System.out.println(result);
		return result;
	}
	
	
	/**
	 * Author锛�  鍛ㄥ噷澶�
     * 鍚戞寚瀹� URL 鍙戦�丳OST鏂规硶鐨勮姹�
     * 
     * @param url
     *            鍙戦�佽姹傜殑 URL
     * @param param
     *            璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋��
     * @return 鎵�浠ｈ〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋�
     */
    public static  String sendPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺�
            URLConnection conn = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬�
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 鍙戦�丳OST璇锋眰蹇呴』璁剧疆濡備笅涓よ
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 鑾峰彇URLConnection瀵硅薄瀵瑰簲鐨勮緭鍑烘祦
            //out = new PrintWriter(conn.getOutputStream());
            //涔辩爜瑙ｅ喅
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); 
            out.write(param); 
            
            // 鍙戦�佽姹傚弬鏁�
            //out.print(param);
            // flush杈撳嚭娴佺殑缂撳啿
            out.flush();
            // 瀹氫箟BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴�
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("鍙戦�� POST 璇锋眰鍑虹幇寮傚父锛�"+e);
            e.printStackTrace();
        }
        //浣跨敤finally鍧楁潵鍏抽棴杈撳嚭娴併�佽緭鍏ユ祦
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    
	
}
